﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using AutoMapper;

namespace Adapter
{
    public class AutomapperTypeAdapter
    {

        public AutomapperTypeAdapter()
        {
            var strpath = AppDomain.CurrentDomain.BaseDirectory;
            if (HttpContext.Current != null)
            {
                strpath = Path.Combine(strpath, "Bin\\");
            }
            var dtoPath = strpath + "DtoCommom.dll";
            var dtoAssembly = System.Reflection.Assembly.LoadFrom(dtoPath);

            var memberMapses = dtoAssembly
                          .GetTypes()
                          .Where(t => t.BaseType.GUID == typeof(DefaultProfile<,>).GUID && !t.IsGenericType)
                          .ToList();

            Mapper.Initialize(m => m.AddProfiles(memberMapses));
        }
        

        /// <summary>
        /// 类型转化
        /// </summary>
        /// <typeparam name="TSource">原类型</typeparam>
        /// <typeparam name="TTarget">目标类型</typeparam>
        /// <param name="source">原类型值</param>
        /// <returns></returns>
        public TTarget Adapt<TSource, TTarget>(TSource source)
            where TSource : class
            where TTarget : class, new()
        {
            return Mapper.Map<TSource, TTarget>(source);
        }

        /// <summary>
        /// 类型转化
        /// </summary>
        /// <typeparam name="TTarget">目标类型</typeparam>
        /// <param name="source">原类型值</param>
        /// <returns></returns>
        public TTarget Adapt<TTarget>(object source) where TTarget : class, new()
        {
            return Mapper.Map<TTarget>(source);
        }


    }
}
